package com.shen.msmservice.controller;

import com.shen.commonutils.Result;
import com.shen.msmservice.service.MsmService;
import com.shen.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    MsmService msmService;
    //发送短信 发送内容有程序生成
    @GetMapping("send/{phone}")
    public Result sendMsm(@PathVariable String phone){
        System.out.println(phone);
        //先从redis里面获取
        String code = redisTemplate.opsForValue().get(phone);
    System.out.println("//////////////////////////////////////////////////");
        if(!StringUtils.isEmpty(code)){ return  Result.ok().message("redis 里面已经存在");}
         code = RandomUtil.getFourBitRandom();
        Map<String,Object> param=new HashMap<>();
        param.put("code",code);
        boolean isSend=msmService.send(param,phone);
        if(isSend) {
            //发送成功 验证码存放在redis里面
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);//五分钟有效时长
            return Result.ok().message("发送成功");
        }
        else  return  Result.error().message("短信验证失败");
    }
}
